package com.godenwater.recv.service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.godenwater.framework.config.SpringUtils;
import com.godenwater.yanyu.YYBuilder;
import com.godenwater.yanyu.utils.ByteUtil;
import com.godenwater.recv.spring.Configurer;
import com.godenwater.web.manager.StationManager;
import com.godenwater.web.rtu.model.RtuStationModel;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.godenwater.core.spring.Application;
import com.godenwater.core.spring.BaseDao;
import org.springframework.data.redis.core.RedisConnectionUtils;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * 1.1报文消费者
 *
 * @author lipujun
 * @ClassName: AbstractMessageConsumer
 * @Description: 通过线程的方式将“报文”解析，然后入库，这是消息进行处理的第一个环节
 * <p>
 * 注意：只启动一个消费者
 * @date Mar 14, 2013
 */
public abstract class AbstractMessageConsumer {

    private static Logger logger = LoggerFactory.getLogger(AbstractMessageConsumer.class);
    private BaseDao dao = SpringUtils.getBean("baseDao");//rtu接收库
    private BaseDao bizdao = SpringUtils.getBean("bizDao");//业务库
    private RedisTemplate redisTemplate;
    /**
     * 武大扬帆数据库链接信息
     */
    //private BaseDao wdyfDao = SpringUtils.getBean("wdyfDao");
    /**
     * 试用于湖北的遥测库
     */
    private BaseDao sjycdbDao = SpringUtils.getBean("sjycdbDao");
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 将原始报文消息写入数据库
     */
    public void writeRtuMessage(String id, String stcd, String protocol,
                                String channel, String funccode, int serial, Date sendtime,
                                int amount, int seq, String message, boolean crcflag, String replayMsg, String ip, Integer port, int recvPort) {
        // 插入原始报文
        String stcd8 = "";
        String stnm = "";//
        String sttp = "";
        //根据设备号获取测站名称及测站8位码信息
        RtuStationModel station = StationManager.getInstance().getStation(stcd);
        if (station != null) {
            stcd8 = station.getStcd8();
            stnm = station.getStnm();
            sttp = station.getSttp();
        }
        Map params = new HashMap();

        params.put("id", id);
        params.put("stcd", stcd);
        params.put("protocol", protocol);
        params.put("sendtime", sendtime);
        params.put("recvtime", new Date(System.currentTimeMillis()));
        params.put("channel", channel);
        params.put("message", message);
        params.put("funccode", funccode);
        params.put("serial", serial);
        params.put("mamount", amount);
        params.put("mseq", seq);
        params.put("flag", crcflag);
        params.put("replaymsg", replayMsg);
        params.put("srcip", ip);
        params.put("srcport", port);
        params.put("recvport", recvPort);
        params.put("stcd8", stcd8);
        params.put("stnm", stnm);
        params.put("sttp", sttp);
        try {
            dao.insert("rtu_message", new String[]{"id", "stcd", "protocol",
                    "sendtime", "recvtime", "channel", "message", "funccode",
                    "serial", "mamount", "mseq", "flag", "replaymsg", "srcip", "srcport", "recvport", "stcd8", "stnm", "sttp"}, params);
            //dao.update("", new Object[]{id,stcd,protocol,sendtime,new Date(System.currentTimeMillis())});
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    public static DateTime writeYYDatetime(byte funccode, Date viewDate) {
        DateTime vd = new DateTime(viewDate);
        switch (funccode) {
            case 0X0B:// 表示雨量加报。
            case 0X09:// 表示水位加报。
                //加报的时间，只需要减去分钟，不需要减1小时
                vd = vd.minusMinutes(vd.getMinuteOfHour()).minusSeconds(vd.getSecondOfMinute());//将分钟减去，以整点开始
                break;
            case 0x07:// 召测报。
                vd = vd.minusHours(1);//减去1小时
                break;
            case 0X0E:// 整点报
                //正点报的，一般情况下会在正点过几分进行发送，但也有提前几分钟发送的现象
                if (vd.getMinuteOfHour() < 5) {
                    vd = vd.minusMinutes(vd.getMinuteOfHour());//将分钟减去，以整点开始
                    vd = vd.minusHours(1);//减去1小时，作为时间起点
                }
                if (vd.getMinuteOfHour() > 55) {
                    vd = vd.minusMinutes(vd.getMinuteOfHour());//将分钟减去，以整点开始
                }
                vd = vd.minusSeconds(vd.getSecondOfMinute());
                break;
        }
        return vd;
    }

    /**
     * 写入燕禹数据的规则
     */
    public void writeYYRainData(String stcd, byte funccode, Date viewDate, String[] f4,
                                int f20, int f1A, byte[] f6) {
        //取出测站数据，需得到测站编码和参数
        RtuStationModel station = StationManager.getInstance().getStation(stcd);
        if (station != null) {
            String stcd8 = station.getStcd8();
            //雨量，从最开始的时间算起
            //DateTime vd = new DateTime(viewDate);
            //vd = vd.minusMinutes(vd.getMinuteOfHour());//将分钟减去，以整点开始
            //vd = vd.minusHours(1);//减去1小时，作为时间起点
            DateTime vd = writeYYDatetime(funccode, viewDate);//时间判断
            for (String f4val : f4) {
                vd = vd.plusMinutes(5);//添加5分钟标记
                if (!StringUtils.endsWithIgnoreCase(f4val, "FF")) {
                    //大于0数据才入库，等于0小于0的数据不入库
                    double tmpval = Double.parseDouble(f4val);
                    //校验数据，判断每五分钟的数据是否大于最大雨强
                    //double maxValue = station.getRainValidMinute() == null ? 0 : station.getRainValidMinute().doubleValue();
                    //if (tmpval > maxValue || tmpval < 0) {
                    //	writeRtuAlarm(stcd8, "P", "", vd.toDate(), "测站" + stcd + "雨量告警！监测数据为：" + tmpval + ";最大雨强为：" + maxValue);
                    //} else {
                    if (tmpval != 0L) {
                        if (funccode == 07) {//召测实时数据，不处理入库
                            writeYYConnvertData(stcd8, vd.toDate(), "1", 23, Double.parseDouble(f4val), 888);
                        } else {
                            //还需要对超过雨强的大小进行过滤，并将超过雨强的写入告警日志
                            writeYYConnvertData(stcd8, vd.toDate(), "1", 23, Double.parseDouble(f4val), 41);
                        }
                    }
                    //}
                }
            }
            //写入日雨量24
            //if (StringUtils.isNotBlank(f1A)) {
            BigDecimal f24val = new BigDecimal(f1A);
            f24val = f24val.multiply(new BigDecimal("0.5"));
            if (funccode == 07) {//召测实时数据，不处理入库
                writeYYConnvertData(stcd8, vd.toDate(), "1", 24, f24val.doubleValue(), 888);
            } else {
                writeYYConnvertData(stcd8, vd.toDate(), "1", 24, f24val.doubleValue(), 41);

            }
            //}
            //写入小时雨量22
            //if (StringUtils.isNotBlank(f20)) {
            BigDecimal f20val = new BigDecimal(f20);
            f20val = f20val.multiply(new BigDecimal("0.5"));
            if (funccode == 07) {//召测实时数据，不处理入库
                writeYYConnvertData(stcd8, vd.toDate(), "1", 22, f20val.doubleValue(), 888);
            } else {
                writeYYConnvertData(stcd8, vd.toDate(), "1", 22, f20val.doubleValue(), 41);
                writeYYVoltage(stcd8, vd.toDate(), f6);
            }
            //}
        }
    }

    public void writeYYRiverData(String stcd, byte funccode, Date viewDate,
                                 String[] f5, byte[] f6) {
        RtuStationModel station = StationManager.getInstance().getStation(stcd);
        if (station != null) {
            String stcd8 = station.getStcd8();
            //2、写入水位,测站类型为2，表示水位站
            if (StringUtils.endsWithIgnoreCase(station.getSttp(), "2") || StringUtils.endsWithIgnoreCase(station.getSttp(), "3") || StringUtils.endsWithIgnoreCase(station.getSttp(), "16")) {
                //DateTime vd = new DateTime(viewDate);
                //vd = vd.minusMinutes(vd.getMinuteOfHour());//将分钟减去
                //vd = vd.minusHours(1);//减去1小时，作为时间起点
                DateTime vd = writeYYDatetime(funccode, viewDate);//时间判断
                for (String f5val : f5) {
                    vd = vd.plusMinutes(5);//添加5分钟标记
                    if (f5val != null && !StringUtils.endsWithIgnoreCase(f5val, "FFFF")) {
                        //不要用double
                        //double f5val_dtm = Double.parseDouble(f5val) + (station.getDtmel()==null?0:station.getDtmel().doubleValue());//将水位与基值相加
                        double dtm = station.getDtmel() == null ? 0 : station.getDtmel().doubleValue();
                        BigDecimal f5bval = new BigDecimal(f5val);
                        f5bval = f5bval.add(new BigDecimal(dtm));

                        //添加极值过滤，超过最高水位，低于最低水位，则不入库，写入告警日志
                        //double high = station.getRiverValidHigh() == null ? dtm + 200 : station.getRiverValidHigh().doubleValue();//如果未设置，则将值设置为高程+200
                        //double low = station.getRiverValidLow() == null ? dtm : station.getRiverValidLow().doubleValue();
                        //if (f5bval.doubleValue() > high || f5bval.doubleValue() < low) {
                        //写入告警数据
                        //	writeRtuAlarm(stcd8, "H", "", vd.toDate(), "测站" + stcd + "水位告警！监测数据为：" + f5bval.doubleValue() + ";最大水位为：" + high + "最低水位为：" + low);
                        //} else {
                        if (funccode == 07) {//召测实时数据，不处理入库
                            writeYYConnvertData(stcd8, vd.toDate(), "1", 11, f5bval.doubleValue(), 888);
                        } else {
                            writeYYConnvertData(stcd8, vd.toDate(), "1", 11, f5bval.doubleValue(), 41);
                        }
                        //}

                    }
                }
                if (funccode != 07) {//召测实时数据，不处理入库
                    writeYYVoltage(stcd8, vd.toDate(), f6);
                }
            }
        }
    }

    //闸位15
    public void writeYYZhaweiData(String stcd, byte funccode, Date viewDate, String[] f8, byte[] f6) {
//		if (StringUtils.isNotBlank(f1A)) {
//			BigDecimal f24val = new BigDecimal(f1A);
//			f24val = f24val.multiply(new BigDecimal("0.5"));
//			writeYYConnvertData(stcd8, vd.toDate(), "1", 24, f24val.doubleValue(), 41);
//		}
        RtuStationModel station = StationManager.getInstance().getStation(stcd);
        if (station != null) {
            String stcd8 = station.getStcd8();
            //DateTime vd = writeYYDatetime(funccode, viewDate);//闸位时间不做变化
            int pos = 0;
            for (String f8val : f8) {
                pos++;
                if (StringUtils.isNotBlank(f8val) && !StringUtils.equalsIgnoreCase(f8val, "FFFF")) {
                    BigDecimal f8bval = new BigDecimal(f8val.trim());
                    if (funccode == 07) {//召测实时数据，不处理入库
                        writeYYConnvertData(stcd8, viewDate, String.valueOf(pos), 15, f8bval.doubleValue(), 888);
                    } else {
                        writeYYConnvertData(stcd8, viewDate, String.valueOf(pos), 15, f8bval.doubleValue(), 41);
                    }
                }
            }
            if (funccode != 07) {//召测实时数据，不处理入库
                writeYYVoltage(stcd8, viewDate, f6);
            }
        }
    }

    //流速	19
    public void writeYYLiusuData(String stcd, byte funccode, Date viewDate, String[] f8, String[] f4, String[] f5, int f20, int f1A, byte[] f6) {
        //1、写入雨量,测站类型为1，表示雨量站
        writeYYRainData(stcd, funccode, viewDate, f4, f20, f1A, f6);

        //2、写入水位,测站类型为2，表示水位站
        writeYYRiverData(stcd, funccode, viewDate, f5, f6);
        RtuStationModel station = StationManager.getInstance().getStation(stcd);
        if (station != null) {
            String stcd8 = station.getStcd8();
            DateTime vd = writeYYDatetime(funccode, viewDate);//时间判断
            for (String f8val : f8) {
                vd = vd.plusMinutes(5);//添加5分钟标记
                if (StringUtils.isNotBlank(f8val) && !StringUtils.equalsIgnoreCase(f8val, "FFFFFFFFFFFFFFFF")) {
                    BigDecimal f8bval = new BigDecimal(f8val.trim());
                    if (funccode == 07) {//召测实时数据，不处理入库
                        writeYYConnvertData(stcd8, vd.toDate(), "1", 19, f8bval.doubleValue(), 888);
                    } else {
                        writeYYConnvertData(stcd8, vd.toDate(), "1", 19, f8bval.doubleValue(), 41);
                    }
                }
            }
            //writeYYVoltage(stcd8, vd.toDate(), f6);
        }
    }

    //OTT(流量)	18
    public void writeYYOttData(String stcd, byte funccode, Date viewDate, int devno, String[] f12, byte[] f6) {
        RtuStationModel station = StationManager.getInstance().getStation(stcd);
        if (station != null) {
            String stcd8 = station.getStcd8();
            DateTime vd = writeYYDatetime(funccode, viewDate);//时间判断
            for (String f12val : f12) {
                vd = vd.plusMinutes(5);//添加5分钟标记
                if (StringUtils.isNotBlank(f12val) && !StringUtils.equalsIgnoreCase(f12val, "FFFFFFFFFFFFFFFF")) {
                    BigDecimal f12bval = new BigDecimal(f12val.trim());
                    if (funccode == 07) {//召测实时数据，不处理入库
                        writeYYConnvertData(stcd8, vd.toDate(), String.valueOf(devno), 18, f12bval.doubleValue(), 888);
                    } else {
                        writeYYConnvertData(stcd8, vd.toDate(), String.valueOf(devno), 18, f12bval.doubleValue(), 41);
                    }
                }
            }
            if (funccode != 07) {//召测实时数据，不处理入库
                writeYYVoltage(stcd8, vd.toDate(), f6);
            }
        }
    }

    //日蒸发32,累计蒸发31
    public void writeYYZhengfaData(String stcd, byte funccode, Date viewDate, int ff31, byte[] f6) {
        RtuStationModel station = StationManager.getInstance().getStation(stcd);
        if (station != null) {
            String stcd8 = station.getStcd8();
            DateTime vd = writeYYDatetime(funccode, viewDate);//时间判断
            vd = vd.plusHours(1);
            BigDecimal ff31bval = new BigDecimal(ff31);
            if (ff31bval.intValue() == 65535) {
                writeYYConnvertData(stcd8, vd.toDate(), "1", 32, 0, 41);
            } else {
                ff31bval = ff31bval.multiply(new BigDecimal("0.1"));
                if (funccode == 07) {//召测实时数据，不处理入库
                    writeYYConnvertData(stcd8, vd.toDate(), "1", 32, ff31bval.doubleValue(), 888);
                } else {
                    writeYYConnvertData(stcd8, vd.toDate(), "1", 32, ff31bval.doubleValue(), 41);
                }
            }
            if (funccode != 07) {//召测实时数据，不处理入库
                writeYYVoltage(stcd8, vd.toDate(), f6);

            }
        }
    }


    /**
     * 写入雨量和水位数据
     *
     * @param stcd
     * @param funccode
     * @param viewDate
     * @param f4
     * @param f5
     * @param f20      时间雨量
     * @param f1A      日雨量
     */
    public void writeYYData(String stcd, byte funccode, Date viewDate, String[] f4, String[] f5, int f20, int f1A, byte[] ff6) {
        //1、写入雨量,测站类型为1，表示雨量站
        writeYYRainData(stcd, funccode, viewDate, f4, f20, f1A, ff6);

        //2、写入水位,测站类型为2，表示水位站
        writeYYRiverData(stcd, funccode, viewDate, f5, ff6);
    }

    public void writeYYData(String stcd, byte funccode, Date viewDate,
                            double voltage, String channel, String[] f4,
                            String[] f5, String f26, String f20, String f1A, String f37,
                            String f39) {

        //取出测站数据，需得到测站编码和参数
        RtuStationModel station = StationManager.getInstance().getStation(stcd);
        if (station != null) {
            String stcd8 = station.getStcd8();
            //燕禹和江西需要添加此拆分
            //1、写入雨量表,测站类型为1，表示雨量站
            if (StringUtils.endsWithIgnoreCase(station.getSttp(), "1") || StringUtils.endsWithIgnoreCase(station.getSttp(), "3")) {
                //雨量，从最开始的时间算起
                //DateTime vd = new DateTime(viewDate);
                //vd = vd.minusMinutes(vd.getMinuteOfHour());//将分钟减去，以整点开始
                //vd = vd.minusHours(1);//减去1小时，作为时间起点
                DateTime vd = writeYYDatetime(funccode, viewDate);//时间判断
                for (String f4val : f4) {
                    vd = vd.plusMinutes(5);//添加5分钟标记
                    if (!StringUtils.endsWithIgnoreCase(f4val, "FF")) {
                        //大于0数据才入库，等于0小于0的数据不入库
                        double tmpval = Double.parseDouble(f4val);
                        //校验数据，判断每五分钟的数据是否大于最大雨强
                        //double maxValue = station.getRainValidMinute() == null ? 0 : station.getRainValidMinute().doubleValue();
                        //if (tmpval > maxValue || tmpval < 0) {
                        //	writeRtuAlarm(stcd8, "P", "", vd.toDate(), "测站" + stcd + "雨量告警！监测数据为：" + tmpval + ";最大雨强为：" + maxValue);
                        //} else {
                        if (tmpval != 0L) {
                            //还需要对超过雨强的大小进行过滤，并将超过雨强的写入告警日志
                            writeYYConnvertData(stcd8, vd.toDate(), "1", 23, Double.parseDouble(f4val), 41);
                        }
                        //}
                    }
                }
                //写入日雨量24
                if (StringUtils.isNotBlank(f1A)) {
                    BigDecimal f24val = new BigDecimal(f1A);
                    f24val = f24val.multiply(new BigDecimal("0.5"));
                    writeYYConnvertData(stcd8, vd.toDate(), "1", 24, f24val.doubleValue(), 41);
                }
                //写入小时雨量22
                if (StringUtils.isNotBlank(f20)) {
                    BigDecimal f20val = new BigDecimal(f20);
                    f20val = f20val.multiply(new BigDecimal("0.5"));
                    writeYYConnvertData(stcd8, vd.toDate(), "1", 22, f20val.doubleValue(), 41);
                }
            }
            //2、写入水位,测站类型为2，表示水位站
            if (StringUtils.endsWithIgnoreCase(station.getSttp(), "2") || StringUtils.endsWithIgnoreCase(station.getSttp(), "3")) {
                //DateTime vd = new DateTime(viewDate);
                //vd = vd.minusMinutes(vd.getMinuteOfHour());//将分钟减去
                //vd = vd.minusHours(1);//减去1小时，作为时间起点
                DateTime vd = writeYYDatetime(funccode, viewDate);//时间判断
                for (String f5val : f5) {
                    vd = vd.plusMinutes(5);//添加5分钟标记
                    if (!StringUtils.endsWithIgnoreCase(f5val, "FFFF")) {
                        //不要用double
                        //double f5val_dtm = Double.parseDouble(f5val) + (station.getDtmel()==null?0:station.getDtmel().doubleValue());//将水位与基值相加
                        double dtm = station.getDtmel() == null ? 0 : station.getDtmel().doubleValue();
                        BigDecimal f5bval = new BigDecimal(f5val);
                        f5bval = f5bval.add(new BigDecimal(dtm));

                        //添加极值过滤，超过最高水位，低于最低水位，则不入库，写入告警日志
                        //double high = station.getRiverValidHigh() == null ? dtm + 200 : station.getRiverValidHigh().doubleValue();//如果未设置，则将值设置为高程+200
                        //double low = station.getRiverValidLow() == null ? dtm : station.getRiverValidLow().doubleValue();
                        //if (f5bval.doubleValue() > high || f5bval.doubleValue() < low) {
                        //写入告警数据
                        //	writeRtuAlarm(stcd8, "H", "", vd.toDate(), "测站" + stcd + "水位告警！监测数据为：" + f5bval.doubleValue() + ";最大水位为：" + high + "最低水位为：" + low);
                        //} else {
                        writeYYConnvertData(stcd8, vd.toDate(), "1", 11, f5bval.doubleValue(), 41);
                        //}

                    }
                }
            }
            //3、写入电压
            writeYYConnvertData(stcd8, viewDate, "1", 51, voltage, 41);

            //闸位数据

            //流量数据

            //流速数据

        } else {

        }
    }

    public void writeYYVoltage(String stcd8, Date viewtime5, byte[] val) {
        String voltageVal5 = YYBuilder.buildDot(ByteUtil.bcd2Str(val), 2);
        double voltage5 = Double.parseDouble(voltageVal5);
        writeYYConnvertData(stcd8, viewtime5, "1", 51, voltage5, 41);
    }

    /**
     * 公用的写入转库表的数据st_rtsr_r，转库程序使用
     * <p>
     * 写入雨量数据，标识符22为小时数据，23为5分钟数据，24为当日累计数据
     * 写入水位数据，标识符为11
     * 写入电压数据，标识符为51（燕禹的原先标识）
     */
    public void writeYYConnvertFiveData(String stcd, Date ymdhm, String devno, int valtyp, double deval, int channel) {
        //System.out.println(">> write convert \t data " +stcd + "\t valtyp " + valtyp + " \t deval "+deval);
        //2、如果无新数据，则添加。如果有数据，则更新，
        if (stcd == null || stcd.equals("")) {
            return;
        }
        Map params = new HashMap();

        params.put("stcd", stcd);
        params.put("ymdhm", ymdhm);
        params.put("devno", devno);
        params.put("valtyp", valtyp);
        params.put("deval", deval);
        params.put("channel", channel);
        SimpleDateFormat sendtimeSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// yyyy-MM-dd
        String tm = sendtimeSdf.format(ymdhm);
        if (999 == channel || 888 == channel) {
            params.put("flag", "1");
        } else {
            params.put("flag", "0");
        }
      /*  String sql = "merge  into ST_RTSR_R A USING (SELECT '" + stcd + "'STCD,'" + tm + "'YMDHM,'" + devno + "'DEVNO,'" + deval + "'deval,'" + valtyp + "'vatyp,'41'channel) " +
                "AS B ON A.STCD=B.STCD AND A.YMDHM=B.YMDHM " +
                "WHEN MATCHED THEN UPDATE SET DEVAL='" + deval + "' " +
                "WHEN NOT MATCHED BY TARGET  THEN INSERT (STCD,YMDHM,DEVNO,DEVAL,VALTYP,CHANNEL) " +
                "VALUES('" + stcd + "','" + tm + "','" + devno + "','" + deval + "','" + valtyp + "','" + channel + "');";
        sjycdbDao.getJdbcTemplate().execute(sql);*/

        //1、先查询，查询条件为测站编码stcd、时间ymdhm、数据类型valtyp、传感器编号devno、数据值deval //sjycdb.dbo.st_rtsr_r
        String searchSql = "select count(*) as cnt from st_rtsr_r_sh where stcd =? and ymdhm=? and valtyp=? ";
        int cnt = 0;

        cnt = sjycdbDao.getJdbcTemplate().queryForRowSet(searchSql, new Object[]{stcd, ymdhm, valtyp}).getRow();

        logger.debug(">>是否有重复数据 " + cnt);
        try {
            if (cnt == 0) {
                //写入新数据//sjycdb.dbo.st_rtsr_r(sqlserver)
                logger.debug(">>写入新数据 " + stcd + " value " + deval);
                sjycdbDao.insert("st_rtsr_r_sh", new String[]{"stcd", "ymdhm", "devno",
                        "valtyp", "deval", "channel", "flag"}, params);
            } else {
                //更新数据 sjycdb.dbo.st_rtsr_r
                logger.debug(">>更新数据 " + stcd + " value " + deval);
                String updateSql = "update st_rtsr_r_sh set  deval = ?,flag=? where stcd =? and ymdhm=? and devno=? and valtyp=? and channel=?";
                sjycdbDao.getJdbcTemplate().update(updateSql, new Object[]{deval, params.get("flag"), stcd, ymdhm, devno, valtyp, channel});
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 公用的写入转库表的数据st_rtsr_r，转库程序使用
     * <p>
     * 写入雨量数据，标识符22为小时数据，23为5分钟数据，24为当日累计数据
     * 写入水位数据，标识符为11
     * 写入电压数据，标识符为51（燕禹的原先标识）
     */
    public void writeYYConnvertData(String stcd, Date ymdhm, String devno, int valtyp, double deval, int channel) {
        //System.out.println(">> write convert \t data " +stcd + "\t valtyp " + valtyp + " \t deval "+deval);
        //2、如果无新数据，则添加。如果有数据，则更新，
        try {
            if (stcd == null || stcd.equals("")) {
                return;
            }
            Map params = new HashMap();

            params.put("stcd", stcd);
            params.put("ymdhm", ymdhm);
            params.put("devno", devno);
            params.put("valtyp", valtyp);
            params.put("deval", deval);
            params.put("channel", channel);
            SimpleDateFormat sendtimeSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// yyyy-MM-dd
            String tm = sendtimeSdf.format(ymdhm);
            if (999 == channel || 888 == channel) {
                params.put("flag", "1");
            } else {
                params.put("flag", "0");
            }
            String sql = "merge  into ST_RTSR_R A USING (SELECT '" + stcd + "'STCD,'" + tm + "'YMDHM,'" + devno + "'DEVNO,'" + deval + "'deval,'" + valtyp + "'vatyp,'41'channel) " +
                    "AS B ON A.STCD=B.STCD AND A.YMDHM=B.YMDHM " +
                    "WHEN MATCHED THEN UPDATE SET DEVAL='" + deval + "' " +
                    "WHEN NOT MATCHED BY TARGET  THEN INSERT (STCD,YMDHM,DEVNO,DEVAL,VALTYP,CHANNEL) " +
                    "VALUES('" + stcd + "','" + tm + "','" + devno + "','" + deval + "','" + valtyp + "','" + channel + "');";
            sjycdbDao.getJdbcTemplate().execute(sql);
/*
            //1、先查询，查询条件为测站编码stcd、时间ymdhm、数据类型valtyp、传感器编号devno、数据值deval //sjycdb.dbo.st_rtsr_r
            String searchSql = "select count(*) as cnt from st_rtsr_r where stcd =? and ymdhm=? and valtyp=? ";
            int cnt = 0;

            cnt = sjycdbDao.getJdbcTemplate().queryForInt(searchSql, new Object[]{stcd, ymdhm, valtyp});

            logger.debug(">>是否有重复数据 " + cnt);

            if (cnt == 0) {
                //写入新数据//sjycdb.dbo.st_rtsr_r(sqlserver)
                logger.debug(">>写入新数据 " + stcd + " value " + deval);
                sjycdbDao.insert("st_rtsr_r", new String[]{"stcd", "ymdhm", "devno",
                        "valtyp", "deval", "channel", "flag"}, params);
            } else {
                //更新数据 sjycdb.dbo.st_rtsr_r
                logger.debug(">>更新数据 " + stcd + " value " + deval);
                String updateSql = "update st_rtsr_r set  deval = ?,flag=? where stcd =? and ymdhm=? and devno=? and valtyp=? and channel=?";
                sjycdbDao.getJdbcTemplate().update(updateSql, new Object[]{deval, params.get("flag"), stcd, ymdhm, devno, valtyp, channel});
            }

 */
        } catch (Exception e) {
           /* sjycdbDao.getConnection().close();
            // set holder isVoid true
            sjycdbDao.unbound();*/
            e.printStackTrace();
        }

    }


    /**
     * 公用的写入转库表的数据st_rtsr_r，转库程序使用
     * <p>
     * 写入雨量数据，标识符22为小时数据，23为5分钟数据，24为当日累计数据
     * 写入水位数据，标识符为11
     * 写入电压数据，标识符为51（燕禹的原先标识）
     */
    public void writeYFConnvertData(String stcd, Date ymdhm, String devno, int valtyp, double deval, int channel) {
        //System.out.println(">> write convert \t data " +stcd + "\t valtyp " + valtyp + " \t deval "+deval);
        //2、如果无新数据，则添加。如果有数据，则更新，
        Map params = new HashMap();

        params.put("stcd", stcd);
        params.put("ymdhm", ymdhm);
        params.put("devno", devno);
        params.put("valtyp", valtyp);
        params.put("deval", deval);
        params.put("channel", channel);
        if (999 == channel) {
            params.put("flag", "1");
        } else {
            params.put("flag", "0");
        }

        //1、先查询，查询条件为测站编码stcd、时间ymdhm、数据类型valtyp、传感器编号devno、数据值deval //sjycdb.dbo.st_rtsr_r
        String searchSql = "select count(*) as cnt from st_rtsr_r where stcd =? and ymdhm=? and valtyp=? and channel!=?";
        int cnt = 0;

        cnt = sjycdbDao.getJdbcTemplate().queryForRowSet(searchSql, new Object[]{stcd, ymdhm, valtyp, 999}).getRow();

        logger.debug(">>是否有重复数据 " + cnt);
        try {
            if (cnt == 0) {
                //写入新数据//sjycdb.dbo.st_rtsr_r(sqlserver)
                logger.debug(">>写入新数据 " + stcd + " value " + deval);
                sjycdbDao.insert("st_rtsr_r", new String[]{"stcd", "ymdhm", "devno",
                        "valtyp", "deval", "channel", "flag"}, params);
            } else {
                //更新数据 sjycdb.dbo.st_rtsr_r
                logger.debug(">>更新数据 " + stcd + " value " + deval);
                String updateSql = "update st_rtsr_r set  deval = ?,flag=? where stcd =? and ymdhm=? and devno=? and valtyp=? and channel=?";
                sjycdbDao.getJdbcTemplate().update(updateSql, new Object[]{deval, params.get("flag"), stcd, ymdhm, devno, valtyp, channel});
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    //获取某一时段雨量数据
    public Double getRain(String stcd, Date ymdhm, int valtyp) {
        Double rain = 0.0;
        try {
            String sql = "select deval from st_rtsr_r where stcd =? and ymdhm=? and valtyp=? and channel=999";
            List<Map<String, Object>> list = sjycdbDao.getJdbcTemplate().queryForList(sql, new Object[]{stcd, ymdhm, valtyp});
            if (null != list && !"".equals(list) && list.size() > 0) {
                rain = Double.valueOf(list.get(0).get("deval").toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rain;
    }

    //获取某一时段真的累积雨量数据
    public Double getRealRain(String stcd, Date ymdhm, int valtyp) {
        Double rain = -1.0;
        try {
            String sql = "select deval from st_rtsr_r where stcd =? and ymdhm=? and valtyp=? and channel=999";
            List<Map<String, Object>> list = sjycdbDao.getJdbcTemplate().queryForList(sql, new Object[]{stcd, ymdhm, valtyp});
            if (null != list && !"".equals(list) && list.size() > 0) {
                rain = Double.valueOf(list.get(0).get("deval").toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rain;
    }

    public void writeYYConnvertDataMysql(String stcd, Date ymdhm, String devno, int valtyp, double deval, int channel) {
        //System.out.println(">> write convert \t data " +stcd + "\t valtyp " + valtyp + " \t deval "+deval);
        //2、如果无新数据，则添加。如果有数据，则更新，
        Map params = new HashMap();

        params.put("stcd", stcd);
        params.put("ymdhm", ymdhm);
        params.put("devno", devno);
        params.put("valtyp", valtyp);
        params.put("deval", deval);
        params.put("channel", channel);
        params.put("flag", "0");
        try {
            //1、先查询，查询条件为测站编码stcd、时间ymdhm、数据类型valtyp、传感器编号devno、数据值deval //sjycdb.dbo.st_rtsr_r
            String searchSql = "select count(*) as cnt from  st_rtsr_r where stcd =? and ymdhm=? and  devno=? and valtyp=?";
            int cnt = 0;

            cnt = dao.getJdbcTemplate().queryForRowSet(searchSql, new Object[]{stcd, ymdhm, devno, valtyp}).getRow();


            if (cnt == 0) {
                //写入新数据//sjycdb.dbo.st_rtsr_r(sqlserver)
                dao.insert("st_rtsr_r", new String[]{"stcd", "ymdhm", "devno",
                        "valtyp", "deval", "channel", "flag"}, params);
            } else {
                //更新数据 sjycdb.dbo.st_rtsr_r
                String updateSql = "update  st_rtsr_r set  deval = ?,flag='0' where stcd =? and ymdhm=? and devno=? and valtyp=? ";
                dao.getJdbcTemplate().update(updateSql, new Object[]{deval, stcd, ymdhm, devno, valtyp});
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 公用的写入转库表的数据st_rtsr_r，转库程序使用
     * <p>
     * 写入雨量数据，标识符22为小时数据，23为5分钟数据，24为当日累计数据
     * 写入水位数据，标识符为11
     * 写入电压数据，标识符为51（燕禹的原先标识）
     */
    public void writeYYConnvertDataSqlserver(String stcd, Date ymdhm, String devno, int valtyp, double deval, int channel) {
        //System.out.println(">> write convert \t data " +stcd + "\t valtyp " + valtyp + " \t deval "+deval);
        //2、如果无新数据，则添加。如果有数据，则更新，
        Map params = new HashMap();

        params.put("stcd", stcd);
        params.put("ymdhm", ymdhm);
        params.put("devno", devno);
        params.put("valtyp", valtyp);
        params.put("deval", deval);
        params.put("channel", channel);
        params.put("flag", "0");

        //1、先查询，查询条件为测站编码stcd、时间ymdhm、数据类型valtyp、传感器编号devno、数据值deval //sjycdb.dbo.st_rtsr_r
        String searchSql = "select count(*) as cnt from st_rtsr_r where stcd =? and ymdhm=? and  devno=? and valtyp=?";
        int cnt = 0;

        cnt = sjycdbDao.getJdbcTemplate().queryForRowSet(searchSql, new Object[]{stcd, ymdhm, devno, valtyp}).getRow();

        try {
            if (cnt == 0) {
                //写入新数据//sjycdb.dbo.st_rtsr_r(sqlserver)
                sjycdbDao.insert("st_rtsr_r", new String[]{"stcd", "ymdhm", "devno",
                        "valtyp", "deval", "channel", "flag"}, params);
            } else {
                //更新数据 sjycdb.dbo.st_rtsr_r
                String updateSql = "update st_rtsr_r set  deval = ?,flag='0' where stcd =? and ymdhm=? and devno=? and valtyp=? ";
                sjycdbDao.getJdbcTemplate().update(updateSql, new Object[]{deval, stcd, ymdhm, devno, valtyp});
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //根据测站和8点的时间获取日雨量
    public String getDayRain(String stcd8, Date endTm) {
        if (null == stcd8 || "".equals(stcd8)) {
            return "";
        }
        //有报文 分钟和秒不为零的情况
        endTm.setMinutes(0);
        endTm.setSeconds(0);
        Date stTm;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(endTm);
        if (endTm.getHours() <= 8) {
            calendar.add(Calendar.DATE, -1);
        }
        stTm = calendar.getTime();
        stTm.setHours(8);
        Map params = new HashMap();
        params.put("stcd", stcd8);
        params.put("enTm", endTm);
        params.put("stTm", stTm);
        try {
            String searchSql = "select  isnull(SUM(isnull(drp,0)),0) from ST_PPTN_R where stcd=? and  TM<=? and TM>?";
            Double cnt;
            cnt = bizdao.getJdbcTemplate().queryForObject(searchSql, new Object[]{stcd8, endTm, stTm}, Double.class);
            return cnt.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 写入小时报
     *
     * @param mid
     * @param stcd
     * @param funccode
     * @param viewDate
     * @param sendDate
     * @param voltage
     * @param channel
     * @param f4
     * @param f5
     * @param f26
     * @param f20
     * @param f1A
     * @param f37
     * @param f39
     * @throws Exception
     */
    public void writeRtuHour(String mid, String stcd, String funccode, Date viewDate,
                             Date sendDate, double voltage, String channel, String[] f4,
                             String[] f5, String f26, String f20, String f1A, String f37,
                             String f39, String f10, String f11, String f13, String f0d, String f06, String f07,
                             String fa3, String fa4, String f02, String f18,
                             String f45, String f27, String ff02, String ff03, String ff04, String ff05, String ffc9, String ff08) throws Exception {

        logger.info("测站号码：" + stcd + "开始写入数据库---------------------------------------------------------------------");
        //写入业务数据库
        RtuStationModel station = StationManager.getInstance().getStation(stcd);
        String sql323InDb = Configurer.getStringProperty("sql323InDb", "0");
        double dtmel = 0;
        if (station != null) {
            dtmel = station.getDtmel() == null ? 0 : Double.parseDouble(station.getDtmel().toString());//高程
        }
        //设置值为655.35的站点为异常报文
        if (f39.equals("655.35")) {
            f39 = "FFFF";
        }
        //亿水泰科 添加高程
        Long rtuCode = Long.parseLong(stcd);
        //String dtmelRange = com.godenwater.recv.spring.Configurer.getStringProperty("dtmel.range", "6001-6400");
        // String[] dtmelRangeList = dtmelRange.split(",");
//        for (int index = 0; index < dtmelRangeList.length; index++) {
//            Long startCode = Long.parseLong(dtmelRangeList[index].split("-")[0]);
//            Long endCode = Long.parseLong(dtmelRangeList[index].split("-")[1]);
//            if (rtuCode >= startCode && rtuCode <= endCode) {
        if (!f39.equals("") && !f39.contains("F") && !f39.contains("f")) {
            try {
                if ((Double.parseDouble(f39) + dtmel) != 0) {
                    DecimalFormat dFormat = new DecimalFormat("#.00");
                    f39 = dFormat.format(Double.parseDouble(f39) + dtmel);
                } else {
                    f39 = "0";
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
//                }
//            }
        }
        /* logger.info("测站号码：" + stcd);*/
        if (station != null) {
            String stcd8 = station.getStcd8();
            String sttp = station.getSttp();
            String flag_water = station.getFlag_water() == null ? "0" : station.getFlag_water();//水位入库
            String flag_rain = station.getFlag_rain() == null ? "0" : station.getFlag_rain();//雨量入库
            double hig = station.getRiverValidHigh() == null ? 0 : station.getRiverValidHigh().doubleValue();
            double low = station.getRiverValidLow() == null ? 0 : station.getRiverValidLow().doubleValue();
            double rainHour = station.getRainWarnHour() == null ? 0 : station.getRainWarnHour().doubleValue();
            double rainDyp = station.getRainWarnDay() == null ? 0 : station.getRainWarnDay().doubleValue();
            //logger.info("测站号码：" + stcd + "获取配置--------------------------------------------------------------------");
            //	写入告警数据 writeRtuAlarm(stcd8, "H", "", vd.toDate(), "测站" + stcd + "水位告警！监测数据为：" + f5bval.doubleValue() + ";最大水位为：" + high + "最低水位为：" + low);
           /* if (f39.equals("FFFFFF") || f39.equals("") || stcd8.equals("")) {
                return;
            }*/
            if (StringUtils.equalsIgnoreCase(sttp, "ZZ") || StringUtils.equalsIgnoreCase(sttp, "H") || StringUtils.equalsIgnoreCase(sttp, "ZQ")) {
                //河道站 判断是否入库 水位数据
                //logger.info("测站号码：" + stcd + "写入水位--------------------------------------------------------------------");
                if (!f39.contains("F") && !f39.equals("") && !stcd8.equals("")) {

                    if (flag_water.equals("1")) {
                        if (hig == 0 && low == 0) {
                            if (sql323InDb.equalsIgnoreCase("1")) {
                                writeBizRiver(stcd8, viewDate, Double.valueOf(f39), bizdao);
                                //写入流量 内蒙要求
                                if (!f27.contains("F") && !f27.equals("")) {
                                    writeBizQRiver(stcd8, viewDate, Double.valueOf(f27), bizdao);
                                }
                            } else {
                                if (Double.valueOf(f39) != 0 && Double.parseDouble(f39) != 436.90) {
                                    writeYYConnvertData(stcd8, viewDate, "1", 12, Double.valueOf(f39), 41);
                                }
                            }
                        } else {
                            if (low <= Double.valueOf(f39) && Double.valueOf(f39) <= hig) {
                                if (sql323InDb.equalsIgnoreCase("1")) {
                                    writeBizRiver(stcd8, viewDate, Double.valueOf(f39), bizdao);
                                    //写入流量 内蒙要求
                                    if (!f27.contains("F") && !f27.equals("")) {
                                        writeBizQRiver(stcd8, viewDate, Double.valueOf(f27), bizdao);
                                    }
                                } else {
                                    if (Double.valueOf(f39) != 0 && Double.parseDouble(f39) != 436.90) {
                                        writeYYConnvertData(stcd8, viewDate, "1", 12, Double.valueOf(f39), 41);
                                    }
                                }

                            } else {
                                writeRtuAlarm(stcd, "H", "", viewDate, "测站编码" + stcd + "水位告警(水位小于最小值，大于最大值拦截)！监测数据为：" + f39 + " 最高水位为：" + hig + " 最低水位为：" + low);
                            }
                        }
                    }
                   /* else {
                        writeRtuAlarm(stcd, "H", "", viewDate, "测站" + stcd + "水位设置不入库！");
                    }*/
                    //logger.info("写入河道------------------------------------------------------------------------");
                }
            }
            if (StringUtils.equalsIgnoreCase(sttp, "RR") || StringUtils.equalsIgnoreCase(sttp, "K")) {
                //水库水文站
                // logger.info("测站号码：" + stcd + "写入水库水位--------------------------------------------------------------------");
                if (!f39.contains("F") && !f39.equals("")) {
                    if (flag_water.equals("1")) {
                        if (hig == 0 && low == 0) {
                            if (sql323InDb.equals("1")) {
                                writeBizRsvr(stcd8, viewDate, Double.valueOf(f39), bizdao);
                            } else {
                                if (Double.valueOf(f39) != 0 && Double.parseDouble(f39) != 436.90) {
                                    writeYYConnvertData(stcd8, viewDate, "1", 11, Double.valueOf(f39), 41);
                                }
                            }
                        } else {
                            if (low <= Double.valueOf(f39) && Double.valueOf(f39) <= hig) {

                                if (sql323InDb.equalsIgnoreCase("1")) {
                                    writeBizRsvr(stcd8, viewDate, Double.valueOf(f39), bizdao);
                                } else {
                                    if (Double.valueOf(f39) != 0 && Double.parseDouble(f39) != 436.90) {
                                        writeYYConnvertData(stcd8, viewDate, "1", 11, Double.valueOf(f39), 41);
                                    }
                                }
                            } else {
                                writeRtuAlarm(stcd, "H", "", viewDate, "测站" + stcd + "水位告警(水位小于最小值，大于最大值拦截)！监测数据为" + f39 + "；最高水位为：" + hig + "；最低水位为：" + low);
                            }
                        }
                        //  logger.info("写入水库------------------------------------------------------------------------");
                    }
                }
            }
            if (StringUtils.equalsIgnoreCase(sttp, "ss") || StringUtils.equalsIgnoreCase(sttp, "s") || StringUtils.equalsIgnoreCase(sttp, "m")) {
                logger.info("写入土壤墒情数据-----------------------------------------------------------------------10cm-" + f10 + " 20cm-" + f11 + " 30cm-" + f13);
                if (sql323InDb.equalsIgnoreCase("1")) {
                    if (StringUtils.isNotBlank(f10) && StringUtils.isNotBlank(f11) && StringUtils.isNotBlank(f13)) {
                        writeBizSoil(stcd8, viewDate, Double.valueOf(f10), Double.valueOf(f11), Double.valueOf(f13), bizdao);
                    }
                } else {
                    //logger.info("测站号码：" + stcd + "|| 国家站号：" + stcd8 + "|| 站类:" + sttp + "时间" + viewDate + " 写入小时雨量数据!");
                    writeYYConnvertData(stcd8, viewDate, "1", 91, Double.valueOf(f10), 41);
                    writeYYConnvertData(stcd8, viewDate, "1", 92, Double.valueOf(f11), 41);
                    writeYYConnvertData(stcd8, viewDate, "1", 93, Double.valueOf(f13), 41);
                }
            }
            if (StringUtils.equalsIgnoreCase(sttp, "bb") || StringUtils.equalsIgnoreCase(sttp, "b")) {
                logger.info("蒸发数据----------------stcd:" + rtuCode + "f06+" + f06 + "--f07:" + f07 + " fa3:" + fa3 + " fa4:" + fa4 + "f02:" + f02 + " f18" + f18 + " f45:" + f45);
                if (sql323InDb.equalsIgnoreCase("1")) {
                    if (StringUtils.isNotBlank(f06)) {
                        writeBizDayev(stcd8, viewDate, Double.valueOf(f06), bizdao);
                    }
                } else {
                    //logger.info("测站号码：" + stcd + "|| 国家站号：" + stcd8 + "|| 站类:" + sttp + "时间" + viewDate + " 写入小时雨量数据!");
                    writeYYConnvertData(stcd8, viewDate, "1", 32, Double.valueOf(f06), 41);

                }
            }
            logger.info("写入小时雨量前------------------------------------------------------------------------" + f1A + "  " + flag_rain);
            //写入小时雨量
            if (!f1A.equals("") && flag_rain.equals("1")) {
                //logger.info("测站号码：" + stcd + "写入雨量--------------------------------------------------------------------");
                if (rainHour != 0) {
                    if (Double.valueOf(f1A) < rainHour) {

                        if (sql323InDb.equalsIgnoreCase("1")) {
                            //F20 日当前降雨量处理
                            writeBizPptn(stcd8, viewDate, Double.valueOf(f1A), 1, bizdao);
                        } else {
                            //logger.info("测站号码：" + stcd + "|| 国家站号：" + stcd8 + "|| 站类:" + sttp + "时间" + viewDate + " 写入小时雨量数据!");
                            writeYYConnvertData(stcd8, viewDate, "1", 22, Double.valueOf(f1A), 41);
                        }
                    } else {
                        writeRtuAlarm(stcd, "P", "", viewDate, "测站" + stcd + "雨量告警(雨量超小时最大值设置)！监测数据为：" + f1A + "；最大时段雨量为：" + rainHour);
                    }
                } else {
                    //logger.info("测站号码：" + stcd + "写入雨量--------------------------------------------------------------------");

                    if (sql323InDb.equalsIgnoreCase("1")) {
                        //取出最新雨量数据
                        writeBizPptn(stcd8, viewDate, Double.valueOf(f1A), 1, bizdao);
                        //写入最新雨量数据
                    } else {
                        writeYYConnvertData(stcd8, viewDate, "1", 22, Double.valueOf(f1A), 41);
                    }
                }
                //logger.info("写入雨量------------------------------------------------------------------------");
            }
            //未设置雨量入库，暂时不写入数据库 20230207
            /* else {
                writeRtuAlarm(stcd, "P", "", viewDate, "测站" + stcd + "雨量告警(未设置雨量入库)！监测数据为：" + f1A + "；最大时段雨量为：" + rainHour);
            }*/
            String intoF1aF20 = (String) Configurer.getStringProperty("intoF1aF20", "0");

            //根据配置计算日雨量
            if (intoF1aF20.equalsIgnoreCase("1")) {
                f20 = getDayRain(stcd8, viewDate);
            }
            /**
             * 八点钟入日雨量，为零的也需要入库
             */
            if (viewDate.getHours() == 8 && viewDate.getMinutes() == 0 && viewDate.getSeconds() == 0) {
                if (flag_rain.equals("1")) {
                    if (Double.valueOf(f20) <= rainDyp) {
                        if (sql323InDb.equalsIgnoreCase("1")) {
                            writeBizPttnDyp(stcd8, viewDate, Double.valueOf(f20), 1, bizdao);
                        } else {
                            writeYYConnvertData(stcd8, viewDate, "1", 24, Double.valueOf(f20), 41);
                        }
                    } else {
                        writeRtuAlarm(stcd, "P", "", viewDate, "测站" + stcd + "雨量告警！监测数据为：" + f20 + "；最大日雨量为：" + rainDyp);
                    }
                }
            }
        }
        writeRtuData("rtu_message_hour", mid, stcd, funccode, viewDate, sendDate, voltage, channel, f4, f5, f26, f20, f1A, f37, f39, f10, f11, f13, f0d, f06, f07, fa3, fa4, f02, f18, f45, f27, ff02, ff03, ff04, ff05, ffc9, ff08);
    }


    //判断五分钟雨量水位数据是否入临时表ST_RTSR_R。//区别于江西与湖北，区分是否入库临时表：1入库，0不入库
    public void writeSL651FiveData(String stcd, String funccode, Date viewDate,
                                   double voltage, String channel, String[] f4, String[] f5) {
//		// 取出测站数据，需得到测站编码和参数
        if (viewDate.getMinutes() != 0 || viewDate.getMinutes() != 0) {
            return;
        }
        RtuStationModel station = StationManager.getInstance().getStation(stcd);
        if (station != null) {
            String stcd8 = station.getStcd8();
            redisTemplate = SpringUtils.getBean("redisTemplate");
            String fiveInDb = "0";
            try {
                if (redisTemplate == null) {
                    logger.info(">> 无监控终端！");
                } else {
                    fiveInDb = redisTemplate.opsForValue().get(stcd8 + "FiveConfig") == null ? "0" : (String) redisTemplate.opsForValue().get(stcd8 + "FiveConfig");
                }
            } catch (Exception ex) {
                RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
                throw new RuntimeException(ex);
            }
            if (fiveInDb.equals("1")) {
                String sttp = station.getSttp();
                String flag_water = station.getFlag_water() == null ? "0" : station.getFlag_water();//水位入库
                String flag_rain = station.getFlag_rain() == null ? "0" : station.getFlag_rain();//雨量入库
                //区分sl651与燕禹协议，是否入雨量数据判断
                viewDate.setMinutes(0);
                viewDate.setSeconds(0);
                /* if (flag_rain.equals("1")) {*/
                DateTime vd = new DateTime(viewDate);
                vd = vd.minusMinutes(vd.getMinuteOfHour());//将分钟减去，以整点开始
                vd = vd.minusHours(1);//减去1小时，作为时间起点
                for (String f4val : f4) {
                    vd = vd.plusMinutes(5);// 添加5分钟标记
                    if (!f4val.equals("FF") && !f4val.equals("")) {
                        // 大于0数据才入库，等于0小于0的数据不入库
                        double tmpval = Double.parseDouble(f4val);
                        if (tmpval != 0L) {
                            writeYYConnvertFiveData(stcd8, vd.toDate(), "1", 23, Double.parseDouble(f4val), 41);
                            logger.info("----------------------单条写入五分钟雨量数据----------------------");
                        }
                    }
                }
                //区分sl651与燕禹协议，是否入水位数据判断
                /*  if (flag_water.equals("1")) {*/
                DateTime vdw = new DateTime(viewDate);
                vdw = vdw.minusMinutes(vdw.getMinuteOfHour());//将分钟减去
                vdw = vdw.minusHours(1);//减去1小时，作为时间起点
                for (String f5val : f5) {
                    vdw = vdw.plusMinutes(5);// 添加5分钟标记
                    if (StringUtils.isNotBlank(f5val) && !"FFFF".equals(f5val)) {
                        double dtm = station.getDtmel() == null ? 0 : station.getDtmel().doubleValue();
                        BigDecimal f5bval = new BigDecimal(f5val);
                        f5bval = f5bval.add(new BigDecimal(dtm));
                        if (f5bval.doubleValue() != 0) {
                            writeYYConnvertFiveData(stcd8, vdw.toDate(), "1", 11, f5bval.doubleValue(), 41);
                            logger.info("----------------------单条写入五分钟水位数据----------------------");
                        }
                    }
                    /*}*/
                }
                // 3、写入电压
                writeYYConnvertFiveData(stcd8, viewDate, "1", 51, voltage, 41);
                logger.info("----------------------写入电压数据----------------------");
                /*}*/
            } else {
                logger.info("sl651站类，" + stcd + "站点不入五分钟数据。");
            }
        } else {
            logger.info("sl651站类，" + stcd + "站点不存在。");
        }
    }

    public void writeBizSoil(String stcd, Date tm, double f10, double f11, double f13, BaseDao db) throws
            ParseException {
        if (null == stcd || "".equals(stcd)) {
            return;
        }
        Map params = new HashMap();
        Calendar ca = Calendar.getInstance();
        //如果分钟和秒不为零，小时数据设置成整点
        if (tm.getMinutes() != 0 || tm.getSeconds() != 0) {
            Date tempDate = new Date(tm.getYear(), tm.getMonth(), tm.getDate(), tm.getHours(), 0, 0);
            ca.setTime(tempDate);
            ca.add(Calendar.HOUR_OF_DAY, 1);
        } else {
            ca.setTime(tm);
        }
        params.put("stcd", stcd);
        params.put("tm", ca.getTime());
        params.put("exkey", "@");
        params.put("slm10", f10);
        params.put("slm20", f11);
        params.put("slm40", f13);
        try {
            //1、先查询，查询条件为测站编码stcd、时间ymdhm、数据类型valtyp、传感器编号devno、数据值deval //sjycdb.dbo.st_rtsr_r
            String searchSql = "select count(*) as cnt from  ST_SOIL_R where stcd =? and tm=? ";
            int cnt = 0;

            cnt = db.getJdbcTemplate().queryForRowSet(searchSql, new Object[]{stcd, ca.getTime()}).getRow();
            if (cnt == 0) {
                //写入新数据//sjycdb.dbo.st_rtsr_r(sqlserver)
                db.insert("ST_SOIL_R", new String[]{"stcd", "tm", "exkey", "slm10", "slm20", "slm40"}, params);
            } else {
                //更新数据 sjycdb.dbo.st_rtsr_r
                String updateSql = "update  ST_SOIL_R set  slm10 = ?,slm20=?,slm40=? where stcd =? and tm=? ";
                db.getJdbcTemplate().update(updateSql, new Object[]{f10, f11, f13, stcd, ca.getTime()});
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void writeBizDayev(String stcd, Date tm, double f06, BaseDao db) throws ParseException {
        if (null == stcd || "".equals(stcd)) {
            return;
        }
        Map params = new HashMap();
        Calendar ca = Calendar.getInstance();
        //如果分钟和秒不为零，小时数据设置成整点
        if (tm.getMinutes() != 0 || tm.getSeconds() != 0) {
            Date tempDate = new Date(tm.getYear(), tm.getMonth(), tm.getDate(), 8, 0, 0);
            ca.setTime(tempDate);
            ca.add(Calendar.HOUR_OF_DAY, 1);
        } else {
            ca.setTime(tm);
        }
        params.put("stcd", stcd);
        params.put("tm", ca.getTime());
        params.put("dev", f06);
        try {
            //1、先查询，查询条件为测站编码stcd、时间ymdhm、
            String searchSql = "select count(*) as cnt from  ST_DAYEV_R where stcd =? and tm=? ";
            int cnt = 0;
            cnt = db.getJdbcTemplate().queryForRowSet(searchSql, new Object[]{stcd, ca.getTime()}).getRow();
            if (cnt == 0) {
                //写入新数据//sjycdb.dbo.st_rtsr_r(sqlserver)
                db.insert("ST_DAYEV_R", new String[]{"stcd", "tm", "dye"}, params);
            } else {
                //更新数据 sjycdb.dbo.st_rtsr_r
                String updateSql = "update  ST_DAYEV_R set  DYE=? where stcd =? and tm=? ";
                db.getJdbcTemplate().update(updateSql, new Object[]{f06, stcd, ca.getTime()});
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入水雨情数据库《雨量表》
     */

    public void writeBizPptn(String stcd, Date tm, double drp, double intv, BaseDao db) throws ParseException {
        if (null == stcd || "".equals(stcd)) {
            return;
        }
        Map params = new HashMap();
        Calendar ca = Calendar.getInstance();
        //如果分钟和秒不为零，小时数据设置成整点
        if (tm.getMinutes() != 0 || tm.getSeconds() != 0) {
            Date tempDate = new Date(tm.getYear(), tm.getMonth(), tm.getDate(), tm.getHours(), 0, 0);
            ca.setTime(tempDate);
            ca.add(Calendar.HOUR_OF_DAY, 1);
        } else {
            ca.setTime(tm);
        }
        params.put("stcd", stcd);
        params.put("tm", ca.getTime());
        params.put("drp", drp);
        params.put("intv", intv);
        try {
            //1、先查询，查询条件为测站编码stcd、时间ymdhm、数据类型valtyp、传感器编号devno、数据值deval //sjycdb.dbo.st_rtsr_r
            String searchSql = "select count(*) as cnt from  st_pptn_r where stcd =? and tm=?";
            int cnt = 0;

            cnt = db.getJdbcTemplate().queryForRowSet(searchSql, new Object[]{stcd, ca.getTime()}).getRow();
            if (cnt == 0) {
                //写入新数据//sjycdb.dbo.st_rtsr_r(sqlserver)
                db.insert("st_pptn_r", new String[]{"stcd", "tm", "drp", "intv"}, params);
            } else {
                //更新数据 sjycdb.dbo.st_rtsr_r
                String updateSql = "update  st_pptn_r set  drp = ?,intv=? where stcd =? and tm=? ";
                db.getJdbcTemplate().update(updateSql, new Object[]{drp, intv, stcd, ca.getTime()});
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 八点写入日雨量数据 lhc 20170727
     *
     * @param stcd
     * @param tm
     * @param dyp
     * @param intv
     * @param db
     */
    public void writeBizPttnDyp(String stcd, Date tm, double dyp, double intv, BaseDao db) {
        if (null == stcd || "".equals(stcd)) {
            return;
        }
        Map params = new HashMap();
        params.put("stcd", stcd);
        params.put("tm", tm);
        params.put("dyp", dyp);
        params.put("intv", intv);
        try {
            //1、先查询，查询条件为测站编码stcd、时间ymdhm、数据类型valtyp、传感器编号devno、数据值deval //sjycdb.dbo.st_rtsr_r
            String searchSql = "select count(*) as cnt from  st_pptn_r where stcd =? and tm=?";
            int cnt = 0;

            cnt = db.getJdbcTemplate().queryForRowSet(searchSql, new Object[]{stcd, tm}).getRow();
            if (cnt == 0) {
                //写入新数据//sjycdb.dbo.st_rtsr_r(sqlserver)
                db.insert("st_pptn_r", new String[]{"stcd", "tm", "dyp", "intv"}, params);
            } else {
                //更新数据 sjycdb.dbo.st_rtsr_r
                String updateSql = "update  st_pptn_r set  dyp = ?,intv=? where stcd =? and tm=? ";
                db.getJdbcTemplate().update(updateSql, new Object[]{dyp, intv, stcd, tm});
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入水雨情数据库《河道表》
     */
    public void writeBizRiver(String stcd, Date tm, double z, BaseDao db) {
        if (null == stcd || "".equals(stcd)) {
            return;
        }
        Map params = new HashMap();
        params.put("stcd", stcd);
        params.put("tm", tm);
        params.put("z", z);
        try {
            //1、先查询，查询条件为测站编码stcd、时间ymdhm、数据类型valtyp、传感器编号devno、数据值deval //sjycdb.dbo.st_rtsr_r
            String searchSql = "select count(*) as cnt from  st_river_r where stcd =? and tm=?";
            int cnt = 0;

            cnt = db.getJdbcTemplate().queryForRowSet(searchSql, new Object[]{stcd, tm}).getRow();
            if (cnt == 0) {
                //写入新数据//sjycdb.dbo.st_rtsr_r(sqlserver)
                db.insert("st_river_r", new String[]{"stcd", "tm", "z"}, params);
            } else {
                //更新数据 sjycdb.dbo.st_rtsr_r
                String updateSql = "update  st_river_r set  z = ? where stcd =? and tm=? ";
                db.getJdbcTemplate().update(updateSql, new Object[]{z, stcd, tm});
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入水雨情数据库《河道表》
     */
    public void writeBizQRiver(String stcd, Date tm, double q, BaseDao db) {
        if (null == stcd || "".equals(stcd)) {
            return;
        }
        Map params = new HashMap();
        params.put("stcd", stcd);
        params.put("tm", tm);
        params.put("q", q);
        try {
            //1、先查询，查询条件为测站编码stcd、时间ymdhm、数据类型valtyp、传感器编号devno、数据值deval //sjycdb.dbo.st_rtsr_r
            String searchSql = "select count(*) as cnt from  st_river_r where stcd =? and tm=?";
            int cnt = 0;

            cnt = db.getJdbcTemplate().queryForRowSet(searchSql, new Object[]{stcd, tm}).getRow();
            if (cnt == 0) {
                //写入新数据//sjycdb.dbo.st_rtsr_r(sqlserver)
                db.insert("st_river_r", new String[]{"stcd", "tm", "q"}, params);
            } else {
                //更新数据 sjycdb.dbo.st_rtsr_r
                String updateSql = "update  st_river_r set  q = ? where stcd =? and tm=? ";
                db.getJdbcTemplate().update(updateSql, new Object[]{q, stcd, tm});
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入水雨情数据库《水库表》
     */
    public void writeBizRsvr(String stcd, Date tm, double rz, BaseDao db) {
        if (null == stcd || "".equals(stcd)) {
            return;
        }
        Map params = new HashMap();
        params.put("stcd", stcd);
        params.put("tm", tm);
        params.put("rz", rz);
        try {
            //1、先查询，查询条件为测站编码stcd、时间ymdhm、数据类型valtyp、传感器编号devno、数据值deval //sjycdb.dbo.st_rtsr_r
            String searchSql = "select count(*) as cnt from  st_rsvr_r where stcd =? and tm=?";
            int cnt = 0;
            logger.info("写入新数据" + tm + "  " + stcd);
            cnt = db.getJdbcTemplate().queryForRowSet(searchSql, new Object[]{stcd, tm}).getRow();
            if (cnt == 0) {
                logger.info("插入");
                db.insert("st_rsvr_r", new String[]{"stcd", "tm", "rz"}, params);
            } else {
                //更新数据 sjycdb.dbo.st_rtsr_r
                logger.info("更新数据");
                String updateSql = "update  st_rsvr_r set  rz = ? where stcd =? and tm=? ";
                db.getJdbcTemplate().update(updateSql, new Object[]{rz, stcd, tm});
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入流量报
     *
     * @param mid
     * @param stcd
     * @param funccode
     * @param viewDate
     * @param sendDate
     * @param voltage
     * @param channel
     * @param f4
     * @param f5
     * @param f26
     * @param f20
     * @param f1A
     * @param f37
     * @param f39
     * @throws Exception
     */
    public void writeRtuFlow(String mid, String stcd, String funccode, Date viewDate,
                             Date sendDate, double voltage, String channel, String[] f4,
                             String[] f5, String f26, String f20, String f1A, String f37,
                             String f39) throws Exception {

        writeRtuData("rtu_message_flow", mid, stcd, funccode, viewDate, sendDate,
                voltage, channel, f4, f5, f26, f20, f1A, f37, f39, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);

    }

    /**
     * 写入测试报
     *
     * @param mid
     * @param stcd
     * @param viewDate
     * @param sendDate
     * @param voltage
     * @param channel
     * @param f37
     * @param f39
     * @throws Exception
     */
    public void writeRtuTest(String mid, String stcd, Date viewDate,
                             Date sendDate, double voltage, String channel, String[] f4,
                             String[] f5, String f26, String f20, String f1A, String f37,
                             String f39) throws Exception {

        writeRtuData("rtu_message_test", mid, stcd, "30", viewDate, sendDate,
                voltage, channel, f4, f5, f26, f20, f1A, f37, f39, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);

    }

    /**
     * 更新测站的中心站地址及密码
     *
     * @param stcd 设备号
     * @param f01  中心站地址
     * @param f03  密码
     */
    public void setCenterPwd(String stcd, String f01, String f03) {
        Map params = new HashMap();


        params.put("stcd", stcd);
        params.put("f01", f01);
        params.put("f03", f03);
        try {
            dao.update("update rtu_station_bc set f01=?,f03=? where stcd=?", new Object[]{f01, f03, stcd});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入报文数据
     *
     * @param mid
     * @param stcd
     * @param viewDate
     * @param sendDate
     * @param voltage
     * @param channel
     * @param f37
     * @param f39
     * @throws Exception
     */
    public void writeRtuData(String rtu_data_table, String mid, String stcd,
                             String funccode, Date viewDate, Date sendDate, double voltage, String channel,
                             String[] f4, String[] f5, String f26, String f20, String f1A,
                             String f37, String f39, String f10, String f11, String f13, String f0d,
                             String f06, String f07, String fa3, String fa4, String f02, String f18, String f45, String f27, String ff02, String ff03, String ff04, String ff05, String ffc9, String ff08) throws
            Exception {
        String stcd8 = "";
        String stnm = "";
        String sttp = "";
        //根据设备号获取测站名称及测站8位码信息
        RtuStationModel station = StationManager.getInstance().getStation(stcd);
        if (station != null) {
            stcd8 = station.getStcd8();
            stnm = station.getStnm();
            sttp = station.getSttp();
        }
        if (stcd == null || stcd.equals("")) {
            return;
        }
        if (f39 != null && f39.length() > 10) {
            return;
        }
        Map params = new HashMap();

        params.put("mid", mid);
        params.put("id", UUID.randomUUID().toString());
        params.put("stcd", stcd);
        params.put("funccode", funccode);
        params.put("viewtime", viewDate);
        params.put("sendtime", sendDate);
        params.put("voltage", voltage);
        params.put("channel", channel);

        params.put("P05", f4[0]);
        params.put("P10", f4[1]);
        params.put("P15", f4[2]);
        params.put("P20", f4[3]);
        params.put("P25", f4[4]);
        params.put("P30", f4[5]);
        params.put("P35", f4[6]);
        params.put("P40", f4[7]);
        params.put("P45", f4[8]);
        params.put("P50", f4[9]);
        params.put("P55", f4[10]);
        params.put("P60", f4[11]);

        params.put("H05", f5[0]);
        params.put("H10", f5[1]);
        params.put("H15", f5[2]);
        params.put("H20", f5[3]);
        params.put("H25", f5[4]);
        params.put("H30", f5[5]);
        params.put("H35", f5[6]);
        params.put("H40", f5[7]);
        params.put("H45", f5[8]);
        params.put("H50", f5[9]);
        params.put("H55", f5[10]);
        params.put("H60", f5[11]);

        params.put("f26", f26);
        params.put("f20", f20);
        params.put("f1a", f1A);

        params.put("f37", f37);
        params.put("f39", f39);

        params.put("recvtime", new Date(System.currentTimeMillis()));
        params.put("dbflag", "0");
        params.put("stcd8", stcd8);
        params.put("stnm", stnm);
        params.put("sttp", sttp);
        params.put("f10", f10);
        params.put("f11", f11);
        params.put("f13", f13);
        params.put("f0d", f0d);

        params.put("f06", f06);
        params.put("f07", f07);
        params.put("fa3", fa3);
        params.put("fa4", fa4);
        params.put("f02", f02);
        params.put("f18", f18);
        params.put("f45", f45);
        params.put("f27", f27);



        params.put("ff02", ff02);//设备温度  28.23
        params.put("ff03", ff03);//信号强度：20
        params.put("ff04", ff04);//管道正累计流量：89m3
        params.put("ff05", ff05);//今日累计流量：89m3
        params.put("ffc9", ffc9);//有功功率 5.6kw
        params.put("ff08", ff08);//开关量1234解析为二进制：0001 0010 0011 0100 低14位分别代表14个开关量信号


        try {
            dao.insert(rtu_data_table, new String[]{"id", "mid", "stcd",
                    "funccode", "viewtime", "sendtime", "voltage", "channel", "P05", "P10",
                    "P15", "P20", "P25", "P30", "P35", "P40", "P45", "P50",
                    "P55", "P60", "H05", "H10", "H15", "H20", "H25", "H30",
                    "H35", "H40", "H45", "H50", "H55", "H60", "F26", "F20",
                    "F1A", "F37", "F39", "recvtime", "dbflag", "stcd8", "stnm", "sttp", "f10", "f11", "f13", "f0d",
                    "f06", "f07", "fa3", "fa4", "f02", "f18", "f45", "f27","ff02","ff03","ff04","ff05","ffc9","ff08"
            }, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入查询回来的数据
     *
     * @param mid
     * @param stcd
     * @param viewDate
     * @param sendDate
     * @param voltage
     * @param channel
     * @param f37
     * @param f39
     * @throws Exception
     */
    public void writeRtuView(String mid, String stcd, Date viewDate,
                             Date sendDate, double voltage, String channel, String[] f4,
                             String[] f5, String f26, String f20, String f1A, String f37,
                             String f39) throws Exception {

        Map params = new HashMap();

        params.put("mid", mid);
        params.put("id", UUID.randomUUID().toString());
        params.put("stcd", stcd);
        params.put("viewtime", viewDate);
        params.put("sendtime", sendDate);
        params.put("voltage", voltage);
        params.put("channel", channel);

        params.put("P05", f4[0]);
        params.put("P10", f4[1]);
        params.put("P15", f4[2]);
        params.put("P20", f4[3]);
        params.put("P25", f4[4]);
        params.put("P30", f4[5]);
        params.put("P35", f4[6]);
        params.put("P40", f4[7]);
        params.put("P45", f4[8]);
        params.put("P50", f4[9]);
        params.put("P55", f4[10]);
        params.put("P60", f4[11]);

        params.put("H05", f5[0]);
        params.put("H10", f5[1]);
        params.put("H15", f5[2]);
        params.put("H20", f5[3]);
        params.put("H25", f5[4]);
        params.put("H30", f5[5]);
        params.put("H35", f5[6]);
        params.put("H40", f5[7]);
        params.put("H45", f5[8]);
        params.put("H50", f5[9]);
        params.put("H55", f5[10]);
        params.put("H60", f5[11]);

        params.put("f26", f26);
        params.put("f20", f20);
        params.put("f1a", f1A);

        params.put("f37", f37);
        params.put("f39", f39);

        params.put("recvtime", new Date(System.currentTimeMillis()));
        params.put("dbflag", "0");
        try {
            dao.insert("rtu_message_view", new String[]{"id", "mid", "stcd",
                    "viewtime", "sendtime", "voltage", "channel", "P05", "P10",
                    "P15", "P20", "P25", "P30", "P35", "P40", "P45", "P50",
                    "P55", "P60", "H05", "H10", "H15", "H20", "H25", "H30",
                    "H35", "H40", "H45", "H50", "H55", "H60", "F26", "F20",
                    "F1A", "F37", "F39", "recvtime", "dbflag"}, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入查询回来的数据
     *
     * @param mid
     * @param stcd
     * @param viewDate
     * @param sendDate
     * @param voltage
     * @param channel
     * @throws Exception
     */
    public void writeRtuHand(String mid, String stcd, Date viewDate,
                             Date sendDate, double voltage, String channel, String content) throws Exception {

        Map params = new HashMap();

        params.put("mid", mid);
        params.put("id", UUID.randomUUID().toString());
        params.put("stcd", stcd);
        params.put("viewtime", viewDate);
        params.put("sendtime", sendDate);
        params.put("voltage", voltage);
        params.put("channel", channel);
        params.put("content", content);

        params.put("recvtime", new Date(System.currentTimeMillis()));
        params.put("dbflag", "0");
        try {
            dao.insert("rtu_message_hand", new String[]{"id", "mid", "stcd",
                    "viewtime", "sendtime", "voltage", "channel", "content", "recvtime", "dbflag"}, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入标识符数据
     *
     * @param mid
     * @param stcd
     * @param sttp
     * @param viewDate
     * @param sendDate
     * @param label
     * @param value
     * @throws Exception
     */
    public void writeRtuSymbol(String mid, String stcd, String sttp,
                               String sendDate, String viewDate, String label, String value)
            throws Exception {

        // 发送时间格式YYMMDDHHmmSS
        SimpleDateFormat sendtimeSdf = new SimpleDateFormat("yyMMddHHmmss");// yyyy-MM-dd
        // HH:mm:ss

        // 观测时间格式YYMMDDHHmm
        SimpleDateFormat viewtimeSdf = new SimpleDateFormat("yyMMddHHmm");// yyyy-MM-dd
        // HH:mm:ss

        Date sendDatetime = sendtimeSdf.parse(sendDate);

        Date viewDatetime = viewtimeSdf.parse(viewDate);

        this.writeRtuSymbol(mid, stcd, sttp, sendDatetime, viewDatetime, label,
                value);

    }

    public void writeRtuSymbol(String mid, String stcd, String sttp,
                               Date sendDate, Date viewDate, String label, String value)
            throws Exception {

        Map params = new HashMap();

        params.put("mid", mid);
        // params.put("id", serial);
        params.put("stcd", stcd);
        params.put("sttp", sttp);
        params.put("viewtime", viewDate);
        params.put("sendtime", sendDate);

        params.put("itemlabel", label.toUpperCase());
        params.put("itemvalue", value.toString());
        params.put("writetime", new Date(System.currentTimeMillis()));

        try {
            dao.insert("rtu_message_item", new String[]{"mid", "stcd",
                    "sttp", "viewtime", "sendtime", "itemlabel", "itemvalue",
                    "writetime"}, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入召测回来的数据
     *
     * @param mid
     * @param stcd
     * @param sttp
     * @param sendDate
     * @param viewDate
     * @param label
     * @param value
     * @throws Exception
     */
    public void writeRtuCallerData(String mid, String stcd, String sttp,
                                   Date sendDate, Date viewDate, String label, String value)
            throws Exception {

        Map params = new HashMap();

        params.put("mid", mid);
        // params.put("id", serial);
        params.put("stcd", stcd);
        params.put("sttp", sttp);
        params.put("viewtime", viewDate);
        params.put("sendtime", sendDate);

        params.put("itemlabel", label.toUpperCase());
        params.put("itemvalue", value.toString());
        params.put("writetime", new Date(System.currentTimeMillis()));

        try {
            dao.insert("rtu_caller_data", new String[]{"mid", "stcd", "sttp",
                    "viewtime", "sendtime", "itemlabel", "itemvalue",
                    "writetime"}, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void writePicPathToDB(String stcd, Date viewtime, String savepath, String stcd8, String picName) {
        logger.info("图片开始写入数据库----------------------------------");
        //logger.info(stcd + "||" + viewtime + "||" + savepath);
        //取出WEB配置地址
        String wdyfInDb = "";
        /*wdyfInDb = com.godenwater.recv.spring.Configurer.getStringProperty("wdyfInDb", "0");*/
        dao = SpringUtils.getBean("baseDao");//rtu接收库
        String center_ip = "";//Configurer.getProperty("center_ip");
        center_ip = com.godenwater.recv.spring.Configurer.getStringProperty("center_ip", "http://223.84.149.58:8888/recvWeb");
        Map params = new HashMap();
        params.put("ID", UUID.randomUUID());
        params.put("STCD", stcd);
        // params.put("id", serial);
        params.put("VIEWTIME", viewtime);
        params.put("SAVEPATH", "http://" + center_ip + savepath);
        params.put("SENDTIME", new Date(System.currentTimeMillis()));
        try {
            dao.insert("rtu_message_img", new String[]{"ID", "STCD", "VIEWTIME", "SAVEPATH", "SENDTIME"}, params);
        } catch (Exception e) {
            e.printStackTrace();
            //logger.info(e.getMessage().toString());
        }

        logger.info("图片结束写入数据库----------------------------------");
    }

    /**
     * 写入RTU电压数据
     *
     * @param stcd
     * @param sendDate
     * @param viewDate
     * @param voltage
     * @throws Exception
     */

    public void writeRtuVoltage(String stcd, Date sendDate, Date viewDate,
                                double voltage) throws Exception {

        Map params = new HashMap();

        params.put("stcd", stcd);
        params.put("sendtime", sendDate);
        params.put("viewtime", viewDate);
        params.put("voltage", voltage);
        params.put("writetime", new Date(System.currentTimeMillis()));

        try {
            dao.insert("rtu_voltage", new String[]{"stcd", "sendtime",
                    "viewtime", "voltage", "writetime"}, params);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // ---------------------------------------------
        try {
            String sql = "update RTU_MESSAGE_NEW set   VIEWTIME = ? , RECVTIME = ? ,   VOLTAGE = ?  where stcd = ?";
            dao.update(
                    sql,
                    new Object[]{viewDate,
                            new Date(System.currentTimeMillis()), voltage, stcd});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @param stcd
     * @param type     类型
     * @param source
     * @param viewDate
     * @param content
     * @throws Exception
     */
    public void writeRtuAlarm(String stcd, String type, String source, Date viewDate, String content) {

        Map params = new HashMap();

        params.put("stcd", stcd);
        params.put("type", type);
        params.put("source", source);
        params.put("dtime", viewDate);
        params.put("sendtm", new Date());
        params.put("content", content);
        params.put("flag", 0);

        try {
            dao.insert("rtu_alarm", new String[]{"stcd", "type", "source", "dtime", "sendtm", "content", "flag"}, params);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 畅通率
     */
    public void writeRtuRate(String stcd, String channel, Date viewDate,
                             int flag) {
        DateTime dt = new DateTime();

        Map params = new HashMap();

        params.put("stcd", stcd);
        params.put("channel", channel);
        params.put("tm", viewDate);
        params.put("flag", flag);
        params.put("writetime", new Date(System.currentTimeMillis()));

        try {
            dao.insert("rtu_rate", new String[]{"stcd", "channel", "tm",
                    "flag", "writetime"}, params);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 昨天
        DateTime yesterday = dt.minusDays(1);

        // DateTime begin = new DateTime("2012-02-01");
        // DateTime end = new DateTime("2012-05-01");
        //
        // //计算区间毫秒数
        // Duration d = new Duration(begin, end);
        // long time = d.getMillis();
        //
        // //计算区间天数
        // Period p = new Period(begin, end, PeriodType.days());
        // int days = p.getDays();
        //
        // //计算特定日期是否在该区间内
        // Interval i = new Interval(begin, end);
        // boolean contained = i.contains(new DateTime("2012-03-01"));
    }

}
